<template>
	<view>
		<web-view :src="webViewUrl" @message="handlerMessage" @load="loadSuccess">
		</web-view>
	</view>
</template>

<script>
	import config from "../../request/config.js";
	export default {
		data() {
			return {
				webViewUrl: "",
				wv: null
			}
		},
		onLoad(params) {
			let path = params.path
			let token = uni.getStorageSync("OaAuth")
			let userInfo = uni.getStorageSync("loginUser")
			let baseUrl = config.WEB_VIEW_URL + path
			this.webViewUrl = baseUrl + "?token=" + token + "&user=" + JSON.stringify(userInfo)
		},
		methods: {
			handlerMessage(event) {
				let data = event.detail.data[0];
				console.log("data=======>",data)
				const arrayBuffer = uni.base64ToArrayBuffer(data.base64)
				const filePath = `${wx.env.USER_DATA_PATH}/` + data.fileName
				this.saveArrayBufferToFile(arrayBuffer, filePath).then(savedFilePath => {
					console.log("savedFilePath===>", savedFilePath);
					uni.openDocument({
						filePath: savedFilePath,
						showMenu: true, //是否可以分享
						success: (res) => {
							console.log("res===>",res);
						},
						fail: (e) => {
							uni.showToast({
								title: '文件打开失败',
								icon: "error"
							})
						}
					})
				})
			},
			saveArrayBufferToFile(arrayBuffer, filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().writeFile({
						filePath: filePath,
						data: arrayBuffer,
						success: (res) => {
							// console.log("res===>",res)
							resolve(filePath);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			loadSuccess() {
				console.log("=======页面加载成功=======")
			},
		}
	}
</script>

<style>
</style>